package com.cocostudio.erpapp.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.util.Log;

import com.cocostudio.erpapp.common.Debug;
import com.cocostudio.erpapp.utils.MD5Util;
import com.cocostudio.erpapp.utils.StorageManager;

public class FileDownloader {
    private static final String TAG = FileDownloader.class.getSimpleName();

    private static String getFileName(String url) {
        int index = url.lastIndexOf("/");
        if (index == -1) {
            return url.substring(index);
        } else {
            return "temp_" + MD5Util.md5(url, true);
        }
    }

    public static File download(Context context, String url) {
        String filename = getFileName(url);
        File file = StorageManager.getFile(context, filename);
        if (file != null && file.exists()) {
            file.delete();
        }
        final HttpClient client = AndroidHttpClient.newInstance("Android");
        final HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }

            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();
                    file = store(context, inputStream, entity.getContentLength(), filename);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (IOException e) {
            getRequest.abort();
            if (Debug.LOGE) {
                Log.e(TAG, "I/O error while retrieving bitmap from " + url, e);
            }
        } catch (IllegalStateException e) {
            getRequest.abort();
            if (Debug.LOGE) {
                Log.e(TAG, "Incorrect URL: " + url);
            }
        } catch (Exception e) {
            getRequest.abort();
            if (Debug.LOGE) {
                Log.e(TAG, "Error while retrieving bitmap from " + url, e);
            }
        } finally {
            if ((client instanceof AndroidHttpClient)) {
                ((AndroidHttpClient) client).close();
            }
        }
        return file;
    }

    private static File store(Context context, InputStream in, long size, String name) throws IOException {
        byte[] buffer = new byte[4096];
        int rlen = 0;
        int type = StorageManager.getBestStorage(context, size);
        OutputStream out = null;
        try {
            out = StorageManager.getOutputStream(context, type, name);
            while ((rlen = in.read(buffer)) != -1) {
                out.write(buffer, 0, rlen);
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return StorageManager.getFile(context, type, name);
    }
}
